import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:svgaplayer_flutter/player.dart';

import '../models/bt_chat_model.dart';
import '../models/bt_message.dart';

class BtChatMessageVoiceWidget extends StatefulWidget {
  const BtChatMessageVoiceWidget({Key? key, required this.item, required this.model}) : super(key: key);

  final BtMessage item;
  final BtChatModel model;

  @override
  State createState() => _BtChatMessageVoiceState();
}

class _BtChatMessageVoiceState extends State<BtChatMessageVoiceWidget> {
  final _player = AudioPlayer();
  StreamSubscription? streamSubscription;

  @override
  void initState() {
    super.initState();

    streamSubscription = _player.playbackEventStream.listen((event) async {
      if (event.processingState == ProcessingState.completed) {
        await _player.stop();
        _player.seek(Duration.zero);
      }
      setState(() {});
    });
  }

  void play(String url) async {
    _player.setUrl(url);
    widget.model.addMarkedReadVoiceMsgId(widget.item.message?.messageId ?? 0);
    await _player.play();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(children: [
      Visibility(
        visible: widget.item.isSender,
        child: Container(
          padding: const EdgeInsets.only(top: 16, right: 18, bottom: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Row(
                children: [
                  Visibility(
                    visible: widget.item.status == 2,
                    child: InkWell(
                      child: Image.asset(
                        'assets/images/bt_icon_chat_sync.png',
                        width: 16,
                        height: 16,
                      ),
                      onTap: () {
                        //widget.model.sendVoiceMessage(path, durationa);
                      },
                    ),
                  ),
                  Visibility(
                    visible: widget.item.status == 0,
                    child: const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        strokeWidth: 1.0,
                        color: Color(0xFF4DB4FF),
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  InkWell(
                    child: Container(
                      margin: const EdgeInsets.only(right: 10),
                      padding: const EdgeInsets.only(left: 14, top: 8, right: 14, bottom: 8),
                      decoration: const BoxDecoration(
                        color: Color(0xFF4DB4FF),
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(12),
                          bottomLeft: Radius.circular(12),
                          topRight: Radius.circular(2),
                          bottomRight: Radius.circular(12),
                        ),
                      ),
                      child: Row(
                        children: [
                          Text(
                            '''${(widget.item.message as RCIMIWVoiceMessage).duration}"''',
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                            ),
                          ),
                          const SizedBox(
                            width: 6,
                          ),
                          _player.playerState.playing
                              ? const SizedBox(
                                  height: 16,
                                  width: 16,
                                  child: SVGASimpleImage(
                                    assetsName: "assets/svga/bt_voice_right.svga",
                                  ),
                                )
                              : Image.asset(
                                  'assets/images/bt_icon_voice_right.png',
                                  width: 20,
                                  height: 18,
                                ),
                        ],
                      ),
                    ),
                    onTap: () {
                      play((widget.item.message as RCIMIWVoiceMessage).remote ?? '');
                    },
                  )
                ],
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(22),
                child: CachedNetworkImage(
                  width: 44,
                  height: 44,
                  fit: BoxFit.fill,
                  imageUrl: widget.model.userAvatar,
                  placeholder: (context, url) => Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22)),
                  ),
                  errorWidget: (context, url, error) => Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22)),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      Visibility(
        visible: !widget.item.isSender,
        child: Container(
          padding: const EdgeInsets.only(left: 18, top: 16, bottom: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(22),
                child: CachedNetworkImage(
                  width: 44,
                  height: 44,
                  fit: BoxFit.fill,
                  imageUrl: widget.model.targetAvatar,
                  placeholder: (context, url) => Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22)),
                  ),
                  errorWidget: (context, url, error) => Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22)),
                  ),
                ),
              ),
              InkWell(
                child: Container(
                  margin: const EdgeInsets.only(left: 10),
                  padding: const EdgeInsets.only(left: 14, top: 8, right: 14, bottom: 8),
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(2),
                      bottomLeft: Radius.circular(12),
                      topRight: Radius.circular(12),
                      bottomRight: Radius.circular(12),
                    ),
                  ),
                  child: Row(
                    children: [
                      _player.playerState.playing
                          ? const SizedBox(
                              height: 16,
                              width: 16,
                              child: SVGASimpleImage(
                                assetsName: "assets/svga/bt_voice_left.svga",
                              ),
                            )
                          : Image.asset(
                              'assets/images/bt_icon_voice_left.png',
                              width: 16,
                              height: 16,
                            ),
                      const SizedBox(
                        width: 8,
                      ),
                      Text(
                        '''${(widget.item.message as RCIMIWVoiceMessage).duration}"''',
                        style: const TextStyle(
                          fontSize: 16,
                          color: Color(0xFF202020),
                        ),
                      ),
                    ],
                  ),
                ),
                onTap: () {
                  play((widget.item.message as RCIMIWVoiceMessage).remote ?? '');
                },
              ),
              Visibility(
                visible: !widget.item.isSender &&
                    !widget.model.isMessageMarkedRead(widget.item.message?.messageId ?? 0),
                child: Container(
                  margin: const EdgeInsets.only(
                    left: 8.0,
                  ),
                  decoration: const BoxDecoration(color: Color(0xFFFF0000), shape: BoxShape.circle),
                  width: 8.0,
                  height: 8.0,
                ),
              )
            ],
          ),
        ),
      ),
    ]);
  }

  @override
  void dispose() {
    _player.dispose();
    streamSubscription?.cancel();
    super.dispose();
  }
}
